package com.tedu.sp11.fallback;

import cn.tedu.web.util.JsonResult;
import org.springframework.cloud.netflix.zuul.filters.route.FallbackProvider;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Component;

import javax.xml.ws.Response;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

@Component
public class ItemFallback implements FallbackProvider {
    /*
    返回"item-service" 此降级类只对商品服务有效
    返回**或者是null，对所有服务都有效
     */

    @Override
    public String getRoute() {
        return "item-service";
    }

    @Override
    public ClientHttpResponse fallbackResponse(String route, Throwable cause) {
        return response();
    }
    private ClientHttpResponse response(){
       return new ClientHttpResponse() {
           public HttpStatus getStatusCode() throws IOException {
               return HttpStatus.OK;
           }

           public int getRawStatusCode() throws IOException {
               return HttpStatus.OK.value();
           }

           public String getStatusText() throws IOException {
               return HttpStatus.OK.getReasonPhrase();
           }

           public void close() {

           }

           public InputStream getBody() throws IOException {
                //JsonResult:{code:401.msg:"获取商品列表失败!",data:null}
               String r = JsonResult.err().msg("获取商品列表失败").toString();
               ByteArrayInputStream in = new ByteArrayInputStream(r.getBytes());
               return in;
           }

           public HttpHeaders getHeaders() {
                //content-Type:application/json
               HttpHeaders h=new HttpHeaders();
               h.setContentType(MediaType.APPLICATION_JSON);
               return  h;
           }
       };
    }
}
